/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package SmartGrid;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Grant
 */
public class ServerFrame extends javax.swing.JFrame {
    private static Connection conn;
    private static Statement stmt;

    
    //create some global variables
    Tariff tariff = new Tariff();
    private double PeakRate = 16.0;
    private double OffPeakRate = 12.0;    
    /**
     * Creates new form ServerFrame
     */
    public ServerFrame() {
        initComponents();
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ServerFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
    }
    
    
    
    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblServer = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtServerOutput = new javax.swing.JTextArea();
        btnUpdateTariff = new javax.swing.JButton();
        jComboBox1 = new javax.swing.JComboBox();
        chkPeak = new javax.swing.JCheckBox();
        chkOffPeak = new javax.swing.JCheckBox();
        btnInvoice = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Smart Grid 2012");
        setBounds(new java.awt.Rectangle(1000, 100, 0, 0));

        lblServer.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblServer.setText("Server Management System Ver 1.0.0");

        txtServerOutput.setColumns(20);
        txtServerOutput.setRows(5);
        jScrollPane1.setViewportView(txtServerOutput);

        btnUpdateTariff.setText("Update Tariff");
        btnUpdateTariff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateTariffActionPerformed(evt);
            }
        });

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "10", "12", "14", "16", "18", "20" }));

        chkPeak.setSelected(true);
        chkPeak.setText("Peak");
        chkPeak.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                chkPeakActionPerformed(evt);
            }
        });

        chkOffPeak.setText("Off Peak");

        btnInvoice.setText("Create Invoice");
        btnInvoice.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInvoiceActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 411, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(btnInvoice)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(6, 6, 6)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(chkPeak)
                                        .addGap(10, 10, 10)
                                        .addComponent(chkOffPeak))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(btnUpdateTariff)
                                        .addGap(35, 35, 35)
                                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(141, 141, 141)
                        .addComponent(lblServer)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(lblServer)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnUpdateTariff)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(chkPeak)
                            .addComponent(chkOffPeak))
                        .addGap(66, 66, 66)
                        .addComponent(btnInvoice))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void chkPeakActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkPeakActionPerformed
        chkOffPeak.invalidate();
    }//GEN-LAST:event_chkPeakActionPerformed

    private void btnUpdateTariffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateTariffActionPerformed
        createConnection();
        txtServerOutput.append("Updating Tariff information");
        shutdown();
        
    }//GEN-LAST:event_btnUpdateTariffActionPerformed

    private void btnInvoiceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInvoiceActionPerformed
        try {
        createConnection();        
        stmt = conn.createStatement();
                ResultSet result = stmt.executeQuery("select * from APP.\"log\"");
                double total = 0.0; 
                while (result.next())
                {txtServerOutput.append("\n" + result.getString(1) + " " + result.getString(2) + " " + result.getString(3) + "Device : " + result.getString(6) + "Amount : " + result.getString(5));
                 //total += result.getString(5);
                }
        //txtServerOutput.append("Total :" + total);
        shutdown();
        } catch (SQLException ex) {
                Logger.getLogger(SmartGridGUI.class.getName()).log(Level.SEVERE, null, ex);
                System.err.println("Exception: "+ex.getMessage());
            }
    }//GEN-LAST:event_btnInvoiceActionPerformed

    
        //java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ServerFrame().setVisible(true);
            }
            
    /**
     * @brief the database connection will be established
     */
    private static void createConnection()
    {
        try
        {
            Class.forName("org.apache.derby.jdbc.ClientDriver");
            
            conn = DriverManager.getConnection("jdbc:derby://localhost/Smartgrid", "root"," "); 
        }
        catch (Exception except)
        {
            except.printStackTrace();
        }
    }
    /**
     * @brief the database and any active connections will be closed
     */
    private static void shutdown()
    {
        try
        {
            if (stmt != null)
            {
                stmt.close();
            }
            if (conn != null)
            {
                DriverManager.getConnection("jdbc:derby://localhost/Smartgrid", "root"," " + ";shutdown=true");
                conn.close();
            }           
        }
        catch (SQLException sqlExcept)
        {
            sqlExcept.printStackTrace();
        }

    }
        //} );
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnInvoice;
    private javax.swing.JButton btnUpdateTariff;
    private javax.swing.JCheckBox chkOffPeak;
    private javax.swing.JCheckBox chkPeak;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblServer;
    private javax.swing.JTextArea txtServerOutput;
    // End of variables declaration//GEN-END:variables
}
